package com.ndood.authenticate.browser.validate.code;

import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import com.ndood.authenticate.core.properties.CommonConstants;
import com.ndood.authenticate.core.validate.code.ValidateCode;
import com.ndood.authenticate.core.validate.code.ValidateCodeRepository;
import com.ndood.authenticate.core.validate.code.ValidateCodeType;

/**
 * 基于session的验证码存取器
 */
@Component
public class SessionValidateCodeRepository implements ValidateCodeRepository {
	/**
	 * 操作session的工具类
	 */
	private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

	@Override
	public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType validateCodeType) {
		sessionStrategy.setAttribute(request, getSessionKey(request, validateCodeType), code);
	}
	
	/**
	 * 构建验证码放入session时的key
	 */
	private String getSessionKey(ServletWebRequest request, ValidateCodeType validateCodeType) {
		return CommonConstants.SESSION_KEY_PREFIX + validateCodeType.toString().toUpperCase();
	}

	@Override
	public ValidateCode get(ServletWebRequest request, ValidateCodeType validateCodeType) {
		return (ValidateCode) sessionStrategy.getAttribute(request, getSessionKey(request, validateCodeType));
	}

	@Override
	public void remove(ServletWebRequest request, ValidateCodeType codeType) {
		sessionStrategy.removeAttribute(request, getSessionKey(request, codeType));
	}

}